package com.woniuxy.email.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Duration;
import java.util.Map;

@Component
@RabbitListener(queues = "q-email") // 指定监听的队列
@Slf4j
public class EmailListener {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private RedisTemplate redisTemplate;

    // 定义监听队列消息的方法
    @RabbitHandler
    public void handlerMsg(Map<String,String> map, Channel channel, Message message, @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        log.info("消息监听器监听到消息，开始处理任务,发送邮件,消息内容：{}",map);
        try {
            // 发送邮件
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(map.get("from"));
            simpleMailMessage.setTo(map.get("to"));
            simpleMailMessage.setSubject(map.get("subject"));
            String code = map.get("text");
            simpleMailMessage.setText("验证码：" + code + ",有效时间5分钟。");
            // 发邮件
            javaMailSender.send(simpleMailMessage);

            // 验证码存储到Redis中, 有效时间5分钟
            redisTemplate.opsForValue().set(map.get("to"),code, Duration.ofMinutes(5));

            // 消费者手动应答
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            e.printStackTrace();
            // 获取重投标记
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if (redelivered) {
                // 重投过的消息消费失败, 拒绝
                channel.basicReject(deliveryTag,false);
            } else {
                // 重投
                channel.basicNack(deliveryTag,false, true);
            }
        }
    }
}
